import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteEntity, getRelationByFrom } from '/@/api/thingsborad/entity/entity'; // 合并导入
import type {
  relationResponse,
  relationByFromParams,
} from '/@/api/thingsborad/entity/model/entityModel';

type FourthLayerData = Record<string, relationResponse[]>;
type ToggleFourthLayer = (item: relationResponse, forceReload?: boolean) => Promise<void>;

export const useEntityDeleter = () => {
  const deleteEntityHandler = async (
    itemId: string,
    parentId: string,
    entityType: string,
    fourthLayerData: FourthLayerData,
    toggleFourth: ToggleFourthLayer,
  ) => {
    try {
      // 先显示确认对话框
      await ElMessageBox.confirm('确定要永久删除该资产吗？此操作不可撤销！', '危险操作', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        center: true,
      });

      // 添加请求参数校验
      if (!entityType || !itemId) {
        ElMessage.warning('删除参数不完整');
        return;
      }

      // 调用删除API时添加响应校验
      await deleteEntity({
        entityType: entityType.toLowerCase(),
        entityId: itemId,
      });

      // 更新本地数据
      if (fourthLayerData[parentId]) {
        fourthLayerData[parentId] = fourthLayerData[parentId].filter(
          (item) => item.to.id !== itemId,
        );
      }

      await toggleFourth(
        {
          fromName: '',
          to: { id: parentId, entityType: 'ASSET' },
          toName: '',
          from: { id: '', entityType: '' },
          type: '',
          typeGroup: '',
          additionalInfo: '',
        },
        true,
      );

      // 刷新父级数据
      const parentItem: relationResponse = {
        to: { id: parentId, entityType: 'ASSET' },
        toName: '',
        from: { id: '', entityType: '' },
        type: '',
        typeGroup: '',
        additionalInfo: '',
      };

      ElMessage.success('资产删除成功');
    } catch (error) {
      const err = error as any; // 修改类型为 any

      // 增强错误处理
      if (err.response?.status) {
        switch (err.response.status) {
          case 401:
            ElMessage.error('请重新登录');
            window.location.reload();
            return;
          case 403:
            ElMessage.error('权限不足');
            return;
          case 404:
            ElMessage.error('资源不存在');
            return;
          default:
            ElMessage.error(`操作失败 (${err.response.status})`);
        }
      }

      // 统一错误提示
      ElMessage.error(`操作失败: ${err.message || '未知错误'}`);
      throw error;
    }
  };
  return { deleteEntity: deleteEntityHandler };
};
